package tpase.client.Handler;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import tpase.client.VO.Ciphertext;
import tpase.client.VO.Message;
import tpase.client.VO.StatusCode;
import tpase.util.Util;

import java.util.Arrays;
import java.util.Map;

public class ClientDownloadFileHandler extends ChannelInboundHandlerAdapter {

    private final String fid;
    private Ciphertext ciphertext;

    public ClientDownloadFileHandler(String fid, Ciphertext ciphertext) {
        this.fid = fid;
        this.ciphertext = ciphertext;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Message request = new Message(StatusCode.DOWNLOAD_FILE_REQUEST);
        Map<String, byte[]> map = request.getMap();
        map.put("fid", fid.getBytes());

        ctx.writeAndFlush(request);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        Message respond = (Message) msg;
        int statusCode = respond.getStatusCode();
        if (statusCode == StatusCode.DOWNLOAD_FILE_RESPONSE) {
            downloadFileResponse(ctx, respond);
            ctx.close();
        }
    }

    private void downloadFileResponse(ChannelHandlerContext ctx, Message respond) {
        byte[] bytes = respond.getMap().get("ciphertext");

        Ciphertext ciphertext2 = Util.jsonToObject(new String(bytes), Ciphertext.class);
        ciphertext.setE(ciphertext2.getE());
        ciphertext.setCom_m(ciphertext2.getCom_m());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("ClientDeleteFileHandler: 发生异常，关闭通道");
        System.out.println(cause.toString());
        ctx.close();
    }
}
